﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Chapter26.Socket
{
    /// <summary>
    /// SocketServerWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SocketReceiveWindow : Window
    {

        public SocketReceiveWindow()
        {
            InitializeComponent();
            Task.Run(new Action(Listen));
        }

        public void Listen()
        {
            var listener = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
            listener.Listen(10);

            while (true)
            {
                var socket = listener.Accept();//等待接收
                var receivedValue = string.Empty;
                while (true)
                {
                    var receivedBytes = new byte[1024];
                    var numBytes = socket.Receive(receivedBytes);//接收字节
                    receivedValue += Encoding.ASCII.GetString(receivedBytes, 0, numBytes);
                    // 转成 ASCII 码,也可以 UTF-8, 甚至不转换使用字节, 即 byte 类型
                    // 在这里使用的  ASCII 码
                    if (receivedValue.IndexOf("[FINAL]") > -1)//收到[FINAL]退出
                    {
                        break;
                    }
                }
                Dispatcher.Invoke(new Action<string>(UpdateDisplay), new object[] { receivedValue });//显示在界面 
                var replayValue = "Message successfully received.";
                var replayBytes = Encoding.ASCII.GetBytes(replayValue);
                socket.Send(replayBytes);//发送成功收到响应
                socket.Shutdown(SocketShutdown.Both);//关闭双方连接，等待下一次接收
                socket.Close();
            }
        }

        private void UpdateDisplay(string text)
        {
            receiveTextBox.Text = text;
        }
    }
}
